package wviz.gui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import javax.jnlp.FileContents;
import javax.jnlp.FileOpenService;
import javax.jnlp.ServiceManager;
import javax.jnlp.UnavailableServiceException;

import org.apache.tika.Tika;

public class FileHandler {

    static private FileOpenService fos = null;  
    static private FileContents fc = null;
    static private String fileName = null;

    // retrieves a reference to the JNLP services
    private static synchronized void initialize() {

        try {
        	
            fos = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");         
        
        } catch (UnavailableServiceException e) {
            fos = null;     
            System.out.println(" services unavailbe. " + e);
        }
    }

    // displays open file dialog and reads selected file using FileOpenService
    public static String open() {
        initialize();
        System.out.println("passed initialize");
        try {
            fc = fos.openFileDialog(null, null);
            return readFromFile(fc);
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
            return null;
        }
    }
    
    // displays open file dialog and reads selected file using FileOpenService
    public static InputStream openStream() {
        initialize();     
        try {
            fc = fos.openFileDialog(null, null);      
            fileName= fc.getName();
            System.out.println("file name is " + fileName);
            return fc.getInputStream();
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
            return null;
        }
    }
    
    public static String getName(){
    	return fileName;
    }

    private static String readFromFile(FileContents fc) throws IOException {
        if (fc == null) {
            return null;
        }
        Tika tika = new Tika();        
        Reader in = tika.parse(fc.getInputStream());
        BufferedReader br = new BufferedReader(in);
        StringBuffer sb = new StringBuffer((int) fc.getLength());
        String line = br.readLine();        
        
        while (line != null) {
            sb.append(line);
            sb.append(" ");
            line = br.readLine();
        }
        br.close();    
        return sb.toString();
    }
}
